package com.sgy.jar_package;

import com.sgy.utils.EPlatform;
import com.sgy.utils.OSInfo;
import org.springframework.util.Assert;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * @author shenguangyang
 * @date 2022-06-27 21:58
 */
public class JarPackageOfRegister {
    /** key 是类名(全名) */
    private static final Map<String, LibParseResult> libInfoCache = new ConcurrentHashMap<>();
    private static class LibParseResult {
        String libRootPath;
        JarPackageInfo libInfo;

        public LibParseResult(String libRootPath, JarPackageInfo libInfo) {
            this.libRootPath = libRootPath;
            this.libInfo = libInfo;
        }
    }
    public static void register(JarPackageInfo libInfo) {
        register(libInfo,  null);
    }

    public static void register(JarPackageInfo libInfo, Supplier<String> targetRootPathOfCustomCallback) {
        Assert.notNull(libInfo, "libInfo is null");
        libInfo.check();
        EPlatform platform = libInfo.getPlatform();
        String key = libInfo.getPackageMarkClass().getName();
        if (platform == OSInfo.getOSName()) {
            if (libInfoCache.containsKey(key)) {
                throw new RuntimeException("lib package mark " + key + " already registered");
            }
            String path = JarPackage.getPath(libInfo, targetRootPathOfCustomCallback == null ? null : targetRootPathOfCustomCallback.get());
            LibParseResult libParseResult = new LibParseResult(path, libInfo);
            libInfoCache.put(key, libParseResult);
        }
    }

    /**
     * 根据包标识子类获取所在包下的数据, 拷贝到主机的哪个目录下了
     * @param packageMarkClass 包标识类
     * @return 本地路径
     * @param <T>
     */
    public static <T extends PackageMark>String getLibRootPath(Class<T> packageMarkClass) {
        Assert.notNull(packageMarkClass, "packageMarkClass is null");
        String key = packageMarkClass.getName();
        LibParseResult libParseResult = libInfoCache.get(key);
        Assert.notNull(libParseResult, "lib package mark [ " + key + "] not registered");
        return libParseResult.libRootPath;
    }
}
